﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;
using System.Configuration;
using System.Data.EntityClient;

namespace WebApplication1
{
    public partial class _Default : System.Web.UI.Page
    {
        public class WebServiceUrl
        {
            public string ServiceName { get; set; }
            public string ServiceFullName { get; set; }
            public string ServiceUrl { get; set; }
        }

        public class ConnectionStringEntity
        {
            public string DBName { get; set; }
            public string DBProvider { get; set; }
            public string DBLocation { get; set; }
            public string UsrLogin { get; set; }
            public string UsrPassword { get; set; }
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack){
            #region  Bind Connection Strings.

                LoadConnectionStringsToSession();

                DataBindConnectionStrings();
                     
            #endregion

            #region  Bind Web Services.
            List<WebServiceUrl> serviceUrls = new List<WebServiceUrl>();

              DirectoryInfo di = new DirectoryInfo(Server.MapPath("~"));
                foreach (FileInfo fi in di.GetFiles())
                {
                    if (fi.Name.EndsWith("asmx"))
                        serviceUrls.Add(new WebServiceUrl
                                            {
                                                ServiceName = fi.Name.Remove(fi.Name.LastIndexOf('.')),
                                                ServiceFullName = fi.Name,
                                                ServiceUrl = "~/" + fi.Name
                                        });
                }

                Session["WebServices"] = serviceUrls;
                DataBindWebServices();

            #endregion
            }
            if(Session["ConnStrings"]== null)  LoadConnectionStringsToSession();
        }

        private void LoadConnectionStringsToSession()
        {
            List<ConnectionStringEntity> connStrings = new List<ConnectionStringEntity>();


            foreach (ConnectionStringSettings dbConnection in ConfigurationManager.ConnectionStrings)
            {
                if (dbConnection.ProviderName == "System.Data.EntityClient")
                {

                    EntityConnectionStringBuilder entityConnectionBuilder =
                         new EntityConnectionStringBuilder(dbConnection.ConnectionString);

                    string provider = String.Empty;
                    switch ((entityConnectionBuilder.Provider))
                    {
                        case "FirebirdSql.Data.FirebirdClient": provider = "FireBird"; break;
                        case "System.Data.SqlClient": provider = "SqlServer"; break;
                    }

                    connStrings.Add(new ConnectionStringEntity
                    {
                        DBName = dbConnection.Name,
                        DBProvider = provider,
                        DBLocation = entityConnectionBuilder.ProviderConnectionString
                    }
                    );
                }
            }

            Session["ConnStrings"] = connStrings;
        }

        private void DataBindConnectionStrings()
        {
            grdConnStrings.DataSource = Session["ConnStrings"];
            grdConnStrings.DataBind();
        }

        private void DataBindWebServices()
        {
            grdWebServices.DataSource = Session["WebServices"];
            grdWebServices.DataBind();
        }

  
        protected void grdWebServices_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            HyperLink objHyperlink = new HyperLink();

            if (e.Row.RowType == DataControlRowType.DataRow)
            {

                WebServiceUrl obj = e.Row.DataItem as WebServiceUrl;

                objHyperlink = e.Row.FindControl("lnkServiceUrl") as HyperLink;

                objHyperlink.NavigateUrl = obj.ServiceUrl;
                objHyperlink.Text = obj.ServiceFullName;

                objHyperlink.Target = "_self";
            }
        }

        protected void grdConnStrings_RowEditing(object sender, GridViewEditEventArgs e)
        {
            grdConnStrings.EditIndex = e.NewEditIndex;
            DataBindConnectionStrings();
        }

        protected void grdConnStrings_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            List<ConnectionStringEntity> list = (List<ConnectionStringEntity>)Session["ConnStrings"];
            Configuration conf = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
            conf.ConnectionStrings.ConnectionStrings.Remove(list[e.RowIndex].DBName);
                          
            list.RemoveAt(e.RowIndex);

            DataBindConnectionStrings();

            conf.Save();
            ConfigurationManager.RefreshSection("ConnectionStrings");          
        }

        protected void grdConnStrings_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            grdConnStrings.EditIndex = -1;
            DataBindConnectionStrings();
        }

        protected void btnInsertCommit_Click(object sender, EventArgs e)
        {
            TextBox txtDBName = grdConnStrings.FooterRow.FindControl("txtDBName") as TextBox;
            TextBox txtDBloc = grdConnStrings.FooterRow.FindControl("txtDBloc") as TextBox;
            //TextBox txtUsrLogin = grdConnStrings.FooterRow.FindControl("txtUsrLogin") as TextBox;
            //TextBox txtUsrPassword = grdConnStrings.FooterRow.FindControl("txtUsrPassword") as TextBox;

            List<ConnectionStringEntity> list = (List<ConnectionStringEntity>)Session["ConnStrings"];
            ConnectionStringEntity newConn = new ConnectionStringEntity();
            newConn.DBName = txtDBName.Text;
         
            switch (((DropDownList)grdConnStrings.FooterRow.FindControl("cmbDBProviders")).SelectedValue)
            {
                case "FireBird":                   
                    newConn.DBProvider = "FireBird";
                    break;

                case "SqlServer":                   
                    newConn.DBProvider = "SqlServer";
                    break;
            }

            newConn.DBLocation = txtDBloc.Text;
            //newConn.UsrLogin = txtUsrLogin.Text;
            //newConn.UsrPassword = txtUsrPassword.Text; 
           
            list.Add(newConn);

            DataBindConnectionStrings();

            EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
            SetProviderSpecificMetadataLocation(entityBuilder, newConn.DBProvider);
            SetProviderSpecificConnectionString(entityBuilder, newConn.DBLocation);

            Configuration conf = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
            conf.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings(
                newConn.DBName,
                entityBuilder.ToString(),
                "System.Data.EntityClient"));

            conf.Save();
            ConfigurationManager.RefreshSection("ConnectionStrings");          
        }

        protected void grdConnStrings_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            List<ConnectionStringEntity> list = (List<ConnectionStringEntity>)Session["ConnStrings"];
            GridViewRow row = grdConnStrings.Rows[e.RowIndex];

            //Update the values.

            ConnectionStringEntity item = list[e.RowIndex];
            item.DBLocation = ((TextBox)row.FindControl("txtDBloc")).Text;
            //item.UsrLogin = ((TextBox)row.FindControl("txtUsrLogin")).Text;
            //item.UsrPassword = ((TextBox)row.FindControl("txtUsrPassword")).Text;
            

            grdConnStrings.EditIndex = -1;
            DataBindConnectionStrings();


            EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
            SetProviderSpecificMetadataLocation(entityBuilder, item.DBProvider);
            SetProviderSpecificConnectionString(entityBuilder, item.DBLocation);

            Configuration conf = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
            conf.ConnectionStrings.ConnectionStrings.Remove(item.DBName);

            conf.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings(
                item.DBName,
                entityBuilder.ToString(),
                "System.Data.EntityClient"));
           
            conf.Save();
            ConfigurationManager.RefreshSection("ConnectionStrings");            
        }

        private static void SetProviderSpecificMetadataLocation(EntityConnectionStringBuilder entityBuilder, string dbProvider)
        {
            switch (dbProvider)
            {
                case "FireBird":

                    entityBuilder.Metadata = @"|DataDirectory|/Schemas/UniversalModel.csdl||DataDirectory|/Schemas/UniversalModel FireBird.ssdl||DataDirectory|/Schemas/UniversalModel.msl";
                    entityBuilder.Provider = "FirebirdSql.Data.FirebirdClient";
                    break;


                case "SqlServer":
                    entityBuilder.Metadata = @"|DataDirectory|/Schemas/UniversalModel.csdl||DataDirectory|/Schemas/UniversalModel SqlClient.ssdl||DataDirectory|/Schemas/UniversalModel.msl";
                    entityBuilder.Provider = "System.Data.SqlClient";
                    break;
            }
        }
        private static void SetProviderSpecificConnectionString(EntityConnectionStringBuilder entityBuilder, string connectionString)
        {
            entityBuilder.ProviderConnectionString = connectionString;
        }
    }
}
